<?php
//kohana项目函数库类
class project{
	
	//返回配置数组，默认配置组名:common
	public static function config($group = 'common'){
		return Kohana::$config->load($group);
	}
	
	//把字符串内的空格替换成通配符，用于关键字查询
	public static function keyword_separate($keywords,$pieces = '.*'){
    	$keywords = explode(' ',$keywords);
		return $pieces.implode($pieces,$keywords).$pieces;
    }

    //提供上传文件真实路径，返回文件虚拟路径
	public static function file_bootstrap($path){
		$path = trim($path,'/ ');
		if (stripos($path,project::config('config')->fileBootstrap) === 0){
			return $path;
		}
		if (stripos($path,project::config('config')->uploadDir) !== 0){
			return project::config('config')->fileBootstrap.'/'.$path;
		}
		return str_replace(project::config('config')->uploadDir,project::config('config')->fileBootstrap,$path);
	}
	
	//提供上传文件虚拟路径，返回文件真实路径
	public static function upload_realpath($path){
		$path = trim($path,'/ ');
		if (stripos($path,project::config('config')->uploadDir) === 0){
			return $path;
		}
		if (stripos($path,project::config('config')->fileBootstrap) !== 0){
			return project::config('config')->uploadDir.'/'.$path;
		}
		return str_replace(project::config('config')->fileBootstrap,project::config('config')->uploadDir,$path);
	}
	
	//TODO
	//生成rewrite,把包括空格在内的各种字符转换成短横杠
	public static function make_rewrite($str,$_id = false){
		if (!strlen($rewrite = trim((string)$str))){
			lib_message::message('rewrite为空');
			return '';
		}
		
		$rewrite = str_replace(array(' ',',','.','--'),'-',strtolower($rewrite));
		
		$m = MON::factory('article');
		if ($_id)
			$m->findOne(array('rewrite'=>$rewrite,'_id'=>array('$ne'=>new MongoId((string)$_id))));
		else
			$m->findOne(array('rewrite'=>$rewrite));
		
		if ($m->loaded()){
			lib_message::message('rewrite已存在');
			return '';
		}
		return $rewrite;
	}
	
	
	//根据参数(可以是字符串或者文章对象)返回文章链接
	public static function a_url($a,$html = true){
		if ($html)
			$ext = '.html';
		else
			$ext = '';
		
		if (is_string($a) && strlen($a))
			return lib_url::base().'a/'.$a.$ext;
		if (isset($a['rewrite']) && strlen($a['rewrite']))
			return lib_url::base().'a/'.$a['rewrite'].$ext;
		if (isset($a['_id']) && strlen($a['_id']))
			return lib_url::base().'a/'.$a['_id'].$ext;
		return lib_url::base();
	}
	
	//返回标签链接
	public static function tag_url($tag){
        if (is_string($tag) && strlen($tag))
			return lib_url::base().'tag/'.$tag;
        return lib_url::base();
	}
	
	//根据_id或rewrite返回对应文章
	public static function find_a($_id_or_rewrite){
		$_id_or_rewrite = (string)$_id_or_rewrite;
		return $a = MON::factory('article')->findOne(array('$or'=>array(
			array('rewrite'=>$_id_or_rewrite),
			array('_id'=>new MongoId($_id_or_rewrite))
		)));
	}
}